<script lang="ts" setup>
import { showFailToast, type FormInstance, type FieldRule, showSuccessToast } from 'vant'
import { ref } from 'vue'
import { loginPassword, codeGet, loginPost } from '@/api/user'
import { useUserStore } from '@/stores'
import { onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'

/*
 表单验证
 1：表单元素值的绑定
 2：绑定表单元素的验证规则
 3：调用form表单内的表单验证方法
   form表单内的validate

 登录接口调用
 1：定义api
 2:导入，在表单验证通过后调用
 3：处理接口参数与返回值的类型
 4：提示一下登录成功

 存储用户信息与token
 1:定义pinia内用户信息存储处理
 2：持久化处理用户信息
 3:在登录页面调用完接口后调用pinia方法存储用户信息

 统一错误处理
 1：拦截接口请求错误（响应拦截）
 2：提示
 3：抛出一个promise错误，不要让代码继续往后走

 发送验证码
 1：点击发送验证码进行局部表单验证(验证手机号)
 2:定义api
 3:点击发送验证通过后调用api
 4:处理返回值的数据类型与请求参数的类型
 5：提示验证码

 短信登录
 1：验证码的表单验证处理（值的绑定）
 2:定义验证码登录api
 3:点击登录在表单验证通过后，分场景调用
 4：处理类型（返回值，请求参数）

*/
const userStore = useUserStore()
const show = ref(false)
const mobile = ref('13230000001')
const password = ref('abc12345')
const code = ref('')
const router = useRouter()
const route = useRoute()
const rules: {
  mobile: FieldRule[]
  password: FieldRule[]
  code: FieldRule[]
} = {
  mobile: [
    { required: true, message: '必填', trigger: 'onChange' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请正确输入手机号',
      trigger: 'onChange'
    }
  ],
  password: [
    { required: true, message: '必填', trigger: 'onChange' },
    {
      pattern: /^\w{8,13}$/,
      message: '请输入8-13位密码',
      trigger: 'onChange'
    }
  ],
  code: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^\d{6}$/, message: '请输入六位数字验证码', trigger: 'onChange' }
  ]
}
const formInstance = ref<FormInstance>()
const agree = ref(false)
// 登录
const submit = async () => {
  if (!agree.value) {
    return showFailToast('请先勾选协议!')
  }
  await formInstance.value?.validate()
  // 登录接口调用
  // if (isPass.value) {
  //   const res = await loginPassword({
  //     mobile: mobile.value,
  //     password: password.value
  //   })
  // } else {
  // const res = await loginPost({
  //   mobile: mobile.value,
  //   code: code.value
  // })
  // }

  const res = isPass.value
    ? await loginPassword({
        mobile: mobile.value,
        password: password.value
      })
    : await loginPost({
        mobile: mobile.value,
        code: code.value
      })
  // console.log('登录返回值', res)
  showSuccessToast('登录成功')
  // 存储用户信息与token
  userStore.setUserInfo(res.data)
  // 跳转到其它页面
  // router.push('/')
  // a==>b===>c
  router.replace((route.query.redirect as string) || '/')
}
// 密码与验证码登录状态切换
const isPass = ref(true) // true:密码登录
// 发送验证码
const totalTime = ref(0)
let timeId = -1
const sendCode = async () => {
  await formInstance.value?.validate('mobile')
  const res = await codeGet({
    mobile: mobile.value,
    type: 'login'
  })

  // 倒计时功能
  totalTime.value = 60
  clearInterval(timeId)
  timeId = setInterval(() => {
    totalTime.value--
    if (totalTime.value <= 0) {
      clearInterval(timeId)
    }
  }, 1000)

  showSuccessToast(res.data.code)
  // console.log('验证码返回值', res)
}

const reUrl = encodeURIComponent(import.meta.env.VITE_APP_URL)

onBeforeUnmount(() => {
  clearInterval(timeId)
})
</script>

<template>
  <div class="login-page">
    <cp-nav-bar rightText="注册98" @click-right="$router.push('/register')" />
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ !isPass ? '密码登录' : '短信验证码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form autocomplete="off" ref="formInstance">
      <van-field
        :rules="rules.mobile"
        v-model="mobile"
        name="mobile"
        placeholder="请输入手机号"
        type="tel"
      ></van-field>
      <!-- 密码 -->
      <van-field
        v-if="isPass"
        :rules="rules.password"
        v-model="password"
        placeholder="请输入密码"
        :type="`${show ? 'text' : 'password'}`"
      >
        <template #right-icon>
          <cp-icon @click="show = !show" :name="`login-eye-${show ? 'on' : 'off'}`" />
        </template>
      </van-field>
      <!-- 短信验证码 -->
      <van-field placeholder="请输入验证码" v-else v-model="code" :rules="rules.code">
        <template #button>
          <span class="code" @click="sendCode" v-if="totalTime === 0">发送验证码</span>
          <span class="code" v-else>{{ totalTime }}s后再次发送</span>
        </template>
      </van-field>

      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" @click="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <a
        @click="userStore.setBackUrl(($route.query.redirect as string) || '/')"
        :href="`https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=${reUrl}`"
        class="icon"
      >
        <img src="@/assets/qq.svg" alt="" />
      </a>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}

.code {
  color: var(--cp-primary);
}
</style>
